import { EventBus } from "./event-bus";
import showMessage from '../components/messageBox';
import {customAlphabet} from "nanoid";
export class Db {
  unavailable = false;

  databaseName = "hexagram";

  nanoid = customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 6);

  constructor() {
    const request = indexedDB.open(this.databaseName, 4);
    request.onsuccess = (event) => {
      this.db = event.target.result;
      window.HexagramAppInterface &&  window.HexagramAppInterface.databaseInitialized();
      this.query("hexagrams");
      this.query("plumagrams");
    };
    request.onerror = () => {
      this.unavailable = false;
      showMessage("数据库加载失败，保存功能将无法使用");
    };
    request.onupgradeneeded = (event) => {
      const db = event.target.result;
      if (!db.objectStoreNames.contains("hexagrams")) {
        this.objectStore = db.createObjectStore("hexagrams", { keyPath: "id" });
        // this.objectStore.createIndex("owner", "owner", { unique: false });
        // this.objectStore.createIndex("question", "question", { unique: false });
      }
      if (!db.objectStoreNames.contains("plumagrams")) {
        this.objectStore = db.createObjectStore("plumagrams", { keyPath: "id" });
      }
    };

    
  }

  save(tableName, data, refresh = true, successFn) {
    if (this.db) {
      this.get(tableName, data.id, (x) => {
        const objectStore = this.db
          .transaction([tableName], "readwrite")
          .objectStore(tableName);
        let request;
        if (x) request = objectStore.put(data);
        else request = objectStore.add(data);
        request.onsuccess = () => {
          if (refresh) this.query(tableName);
          if(successFn && typeof successFn === "function") successFn.call(successFn);
        };
      });
    }
  }

  get(tableName, id, success) {
    const objectStore = this.db
      .transaction([tableName])
      .objectStore(tableName);
    const request = objectStore.get(id);
    request.onsuccess = (event) => {
      if (success) success(event.target.result);
    };
  }

  delete(tableName, id, success) {
    const request = this.db
      .transaction([tableName], "readwrite")
      .objectStore(tableName)
      .delete(id);
    request.onsuccess = (event) => {
      if (success) success(event.target.result);
      const index = this[tableName].findIndex((x) => x.id == id);
      this[tableName].splice(index, 1);
    };
  }

  query(tableName) {
    const objectStore = this.db
      .transaction([tableName])
      .objectStore(tableName);
    this[tableName] = [];
    objectStore.openCursor(null, "prev").onsuccess = (event) => {
      const cursor = event.target.result;
      if (cursor) {
        this[tableName].push(cursor.value);
        cursor.continue();
      } else {
        EventBus.$emit("customer-data-loaded", this[tableName]);
      }
    };
  }

  importData(tableName, data) {
    if (data && data.length && data instanceof Array) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].id) this.save(tableName, data[i], i == data.length - 1);
      }
    }
  }

  importFromApp(fileContent, finished){
    const data = JSON.parse(fileContent);
    if(data.tableName == "hexagrams" || data.tableName == "plumagrams"){
      if(data.data && data.data.length > 0){
        for (let i = 0; i < data.data.length; i++) {
          if (data.data[i].id) this.save(data.tableName, data.data[i], finished);
        }
      }
    }
  }

  generateId(){
    return new Date().getTime() + this.nanoid();
  }
}
